from rest_framework import serializers
from .models import Resume, Education, WorkExperience,  ResumeTemplate, ResumeAnalysis, JobRecommendation, CompanyRecommendation

class EducationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Education
        fields = '__all__'

class WorkExperienceSerializer(serializers.ModelSerializer):
    class Meta:
        model = WorkExperience
        fields = '__all__'




class ResumeSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    educations = EducationSerializer(many=True, required=False)
    work_experiences = WorkExperienceSerializer(many=True, required=False)

    class Meta:
        model = Resume
        fields = '__all__'

    def create(self, validated_data):
        educations_data = validated_data.pop('educations', [])
        work_experiences_data = validated_data.pop('work_experiences', [])
        validated_data.pop('project_experiences', None)
        validated_data.pop('skills', None)
        validated_data.pop('attachments', None)
        validated_data.pop('user', None)  # 关键：确保 user 字段被移除
        user = self.context['request'].user
        print('user:', user, type(user))
        resume = Resume.objects.create(user=user, **validated_data)
        for edu in educations_data:
            Education.objects.create(resume=resume, **edu)
        for work in work_experiences_data:
            WorkExperience.objects.create(resume=resume, **work)
        return resume

    def update(self, instance, validated_data):
        # 可根据需要实现嵌套更新
        return super().update(instance, validated_data)

class ResumeTemplateSerializer(serializers.ModelSerializer):
    class Meta:
        model = ResumeTemplate
        fields = '__all__'


# 简历分析相关序列化器
class JobRecommendationSerializer(serializers.ModelSerializer):
    class Meta:
        model = JobRecommendation
        fields = '__all__'


class CompanyRecommendationSerializer(serializers.ModelSerializer):
    class Meta:
        model = CompanyRecommendation
        fields = '__all__'


class ResumeAnalysisSerializer(serializers.ModelSerializer):
    job_recommendations = JobRecommendationSerializer(many=True, read_only=True)
    company_recommendations = CompanyRecommendationSerializer(many=True, read_only=True)
    
    class Meta:
        model = ResumeAnalysis
        fields = '__all__'
        read_only_fields = ['extracted_text', 'analysis_result', 'improvement_suggestions', 
                           'recommended_positions', 'recommended_companies', 'status', 
                           'error_message', 'completed_at']


class ResumeAnalysisCreateSerializer(serializers.ModelSerializer):
    """用于创建简历分析的序列化器"""
    
    class Meta:
        model = ResumeAnalysis
        fields = ['resume_file', 'original_filename']
    
    def validate_resume_file(self, value):
        """验证上传的文件"""
        # 检查文件大小（限制为10MB）
        if value.size > 10 * 1024 * 1024:
            raise serializers.ValidationError("文件大小不能超过10MB")
        
        # 检查文件类型
        allowed_extensions = ['.pdf', '.docx', '.doc', '.txt', '.jpg', '.jpeg', '.png']
        file_ext = value.name.lower()
        if not any(file_ext.endswith(ext) for ext in allowed_extensions):
            raise serializers.ValidationError(f"不支持的文件格式。支持的格式：{', '.join(allowed_extensions)}")
        
        return value
    
    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class ResumeAnalysisResultSerializer(serializers.ModelSerializer):
    """用于返回分析结果的序列化器"""
    
    class Meta:
        model = ResumeAnalysis
        fields = ['id', 'original_filename', 'extracted_text', 'analysis_result', 
                 'improvement_suggestions', 'recommended_positions', 'recommended_companies',
                 'status', 'error_message', 'created_at', 'completed_at']